#include <learn/check_gl.h>
#include <learn/gl/gl_callback.h>

using namespace xi::gl;
using namespace xi::geom;

// 四面体的顶点
Vec3f v[4] = {Vec3f{0.5f, 0.0f, 0.5f}, Vec3f{-0.5f, 0.0f, 0.5f}, Vec3f{0.0f, 0.0f, -0.5f}, Vec3f{0.0f, 0.5f, 0.0f}};

// 绘制三角形
void triangle(Vec3f a, Vec3f b, Vec3f c)
{
    glBegin(GL_TRIANGLES);
    glVertex3f(a.x(), a.y(), a.z());
    glVertex3f(b.x(), b.y(), b.z());
    glVertex3f(c.x(), c.y(), c.z());
    glEnd();
}

// 绘制四面体
void tetrahedron(Vec3f a, Vec3f b, Vec3f c, Vec3f d)
{
    glColor3f(1, 0, 0);
    triangle(a, b, c);
    glColor3f(0, 1, 0);
    triangle(b, c, d);
    glColor3f(0, 0, 1);
    triangle(c, d, a);
    glColor3f(1, 1, 1);
    triangle(d, a, b);
}

// 四面体细分
void divide_tetrahedron(Vec3f a, Vec3f b, Vec3f c, Vec3f d, int depth)
{
    if (depth > 0)
    {
        // 计算中点位置
        Vec3f v1, v2, v3, v4, v5, v6;
        for (int i = 0; i < 3; i++)
        {
            v1[i] = (a[i] + d[i]) / 2;
            v2[i] = (b[i] + d[i]) / 2;
            v3[i] = (c[i] + d[i]) / 2;
            v4[i] = (a[i] + b[i]) / 2;
            v5[i] = (b[i] + c[i]) / 2;
            v6[i] = (c[i] + a[i]) / 2;
        }
        // 分别细分
        divide_tetrahedron(d, v1, v2, v3, depth - 1);
        divide_tetrahedron(v1, a, v4, v6, depth - 1);
        divide_tetrahedron(v2, v4, b, v5, depth - 1);
        divide_tetrahedron(v3, v6, v5, c, depth - 1);
    }
    else
    {
        tetrahedron(a, b, c, d);
    }
}

void init()
{
    CHECK_GL(glEnable(GL_DEPTH_TEST));
    CHECK_GL(glPolygonMode(GL_FRONT_AND_BACK, GL_LINE));
}

void render()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    divide_tetrahedron(v[0], v[1], v[2], v[3], 4);
}

int main()
{
    if (!glfwInit())
    {
        std::cerr << "Failed to initialize GLFW" << std::endl;
        return -1;
    }

    GLFWwindow *window = glfwCreateWindow(800, 600, "Three Stars", nullptr, nullptr);
    if (!window)
    {
        std::cerr << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    // 注册函数
    glfwSetFramebufferSizeCallback(window, GLFWWindowResize);
    glfwSetScrollCallback(window, GLFWScrollCallback);
    glfwSetMouseButtonCallback(window, GLFWMouseButtonCallback);
    glfwSetCursorPosCallback(window, GLFWCursorPosCallback);
    glfwSetKeyCallback(window, GLFWKeyCallback);
    glfwSetDropCallback(window, GLFWDropCallback);

    init();
    while (!glfwWindowShouldClose(window))
    {
        // 视图变换
        transform(window);

        render();
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();

    return 0;
}
